package cool.taomu.toolkit.rpc.thrift.client.service

import com.google.common.base.Function
import java.util.concurrent.ConcurrentHashMap
import org.apache.commons.pool2.impl.GenericObjectPool
import org.apache.commons.pool2.impl.GenericObjectPoolConfig
import org.apache.thrift.protocol.TCompactProtocol
import org.apache.thrift.protocol.TProtocol
import org.apache.thrift.transport.TTransport
import org.apache.thrift.transport.layered.TFramedTransport
import org.slf4j.LoggerFactory

@Deprecated
class ThriftClient {
	val static LOG = LoggerFactory.getLogger(ThriftClient);

	val static poolMap = new ConcurrentHashMap<String, GenericObjectPool<TTransport>>();

	def void removePoolObject(String host, int port) {
		var poolKey = #[host, port].join("#");
		var obj = poolMap.get(poolKey);
		poolMap.remove(poolKey);
		obj.close();

	}

	def void close(String host, int port) {
		var poolKey = #[host, port].join("#");
		if (poolMap.containsKey(poolKey)) {
			var pool = poolMap.get(poolKey)
			poolMap.remove(poolKey);
			pool.close;
		}
	}

	def static void client(String host, int port, Function<TProtocol, Void> client) {
		client(host, port, Integer.MAX_VALUE, 50000, client);
	}

	def static void client(String host, int port, int maxLength, int timeout, Function<TProtocol, Void> client) {
		LOG.debug("连接服务器=>{}:{}", host, port);
		var poolKey = #[host, port].join("#");
		if (!poolMap.containsKey(poolKey)) {
			LOG.debug("创建连接池")
			var config = new GenericObjectPoolConfig<TTransport>();
			config.setMaxTotal(10); // 最大连接数
			config.setMinIdle(2); // 最小空闲连接数
			config.setMaxIdle(5); // 最大空闲连接数
			// 启用连接验证
			config.setTestOnBorrow(true); // 借用对象时验证
			config.setTestWhileIdle(true); // 空闲时验证
			var pool = new GenericObjectPool<TTransport>(new cool.taomu.toolkit.rpc.thrift.service.ThriftConnectionFactory(host, port, timeout), config);
			poolMap.put(poolKey, pool);
		}

		LOG.debug("获取连接池中的连接");
		var socket = poolMap.get(poolKey).borrowObject;
		LOG.debug("连接到服务器操作1");
		try (var tTransport = new TFramedTransport(socket, maxLength)) {
			var protocol = new TCompactProtocol(tTransport);
			LOG.debug("连接到服务器操作2");
			client.apply(protocol);
		} catch (Exception e) {
			e.printStackTrace
		} finally {
			try {
				LOG.debug("执行连接归还操作");
				poolMap.get(poolKey).returnObject(socket); // 归还连接
			} catch (Exception ignored) {
				ignored.printStackTrace
			}
		}
	}

}
